package com.ltmt.es.persistence.utils;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;

import com.ltmt.es.persistence.repository.PrimitivaHistoricCombinationRepository;


public class SpringDataUtil {
	
	private static JpaRepositoryFactory jpaRepositoryFactory;
	private static EntityManager entityManager;

	private static PrimitivaHistoricCombinationRepository phcr;
	
	private static Log log = LogFactory.getLog(SpringDataUtil.class);
	
	
		
		public static JpaRepositoryFactory getRepositoryFactory(){
			try {
				if (jpaRepositoryFactory == null){
					EntityManagerFactory emf = Persistence.createEntityManagerFactory("LTMT_SpringData_Persistence", System.getProperties());
					entityManager = emf.createEntityManager();
					entityManager.setFlushMode(FlushModeType.AUTO);
					jpaRepositoryFactory = new JpaRepositoryFactory(entityManager);
				}
				
			} catch (Exception ex){
				
			}
			
			return jpaRepositoryFactory;
		
			
	}
		
	public static PrimitivaHistoricCombinationRepository getRepository(){
		
		if (phcr == null)
			phcr = getRepositoryFactory().getRepository(PrimitivaHistoricCombinationRepository.class);
		return phcr;
	}
	
	
	public static EntityManager getEntityManager(){
		return entityManager;
	}
	
	public static void startTransaction(){
		if (!entityManager.getTransaction().isActive())
			entityManager.getTransaction().begin();
	}
		
	
}
